package com.dc.wifi.main.model

import android.app.Application
import android.view.View
import androidx.databinding.Observable
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.lifecycle.MutableLiveData
import com.dc.netlib.base.BaseAndroidViewModel
import com.dc.netlib.bean.UserInfoBean
import com.dc.netlib.impl.NoMultiClickListener
import com.dc.netlib.utils.ToastUtil
import com.dc.wifi.R
import com.dc.wifi.main.repository.LoginRepository
import kotlinx.coroutines.delay
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.ToastUtils
import com.dc.netlib.bean.request.LoginRequestBean
import kotlinx.coroutines.launch

class LoginViewModel(application: Application) :
    BaseAndroidViewModel<LoginRepository>(application = application) {
    val pwd = ObservableField<String>("123456")
    val username = ObservableField<String>("lufei456")
    val btnLoginEnable = ObservableBoolean(false)

    //    val btnLoginBackgroundResId = ObservableInt(getColor(R.color.color_aaa))
    val loginLiveData = MutableLiveData<UserInfoBean?>()

    fun loginClick(view: View) {
        view.setOnClickListener(NoMultiClickListener {
            val userName = username.get()
            val pwd = pwd.get()
            if (userName.isNullOrBlank() || pwd.isNullOrBlank()) {
                ToastUtil.show(getString(R.string.login_error_tip))
                return@NoMultiClickListener
            }
            login(userName, pwd)
        })
    }

    fun login(username: String, pwd: String) {
        val request = LoginRequestBean(username = username, password = pwd)
        //模拟登录
//        viewModelScope.launch {
//            delay(400)
//            loginLiveData.value = null
//        }

        launchApiCall({
            repository.login(username,pwd)
                      }, {
            if (it.data == null) {
                return@launchApiCall
            }
//            ToastUtils.showShort(it.errorMsg)
            loginLiveData.postValue(it.data)
        }, {
            loginLiveData.value = null
        })
    }


    private val observableCallBack: Observable.OnPropertyChangedCallback =
        object : Observable.OnPropertyChangedCallback() {
            override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                setLoginBtnEnable()
            }
        }

    init {
        pwd.addOnPropertyChangedCallback(observableCallBack)
        username.addOnPropertyChangedCallback(observableCallBack)
    }

    private fun setLoginBtnEnable() {
        val userName = username.get()
        val pwd = pwd.get()
        if (userName.isNullOrBlank() || pwd.isNullOrBlank()) {
            btnLoginEnable.set(false)
//            btnLoginBackgroundResId.set(getColor(R.color.color_aaa))
            return
        }
        btnLoginEnable.set(true)
//        btnLoginBackgroundResId.set(getColor(R.color.black))
    }


}